---@diagnostic disable: undefined-field
require("sys")
local uartid=1
local dcom = {}
dcom.buff = zbuff.create(2048)
local readState=false
local function readRfid()
    while true do
        sys.wait(100)
        if(readState and sendData) then
            return
        end
        readState=true
        -- log.info("------读取一次卡信息------")
        -- 读取一次卡信息
        uart.write(uartid,string.char(0xBB, 0x00, 0x22, 0x00, 0x00, 0x22, 0x7E))       
    end
    
end
local function ComInit()
    local result = uart.setup(
        uartid,--串口id
        115200,--波特率
        8,--数据位
        1--停止位
    )    
    -- 串口讀取到的數據的回調
    uart.on(uartid, "receive", function(id, len)
        local s = ""
        -- log.info("uart", "start")
        repeat
            -- 如果是air302, len不可信, 传1024
            -- s = uart.read(id, 1024)
            s = uart.read(id, len)
            if #s > 0 then -- #s 是取字符串的长度
                -- 如果传输二进制/十六进制数据, 部分字符不可见, 不代表没收到
                -- 关于收发hex值,请查阅 https://doc.openluat.com/article/583
                local str,num=s:toHex()
        
                if str =="BB01FF000115167E" then
                    break
                end
                
                log.info("uart", "receive", id, str)
                sys.publish("ddn_event", {src = "dcom",evt = "DATA", dat = str})
                -- log.info("uart", "receive", id, #s)
                -- log.info("uart", "receive", id, #s, s:toHex())
            end
            if #s == len then
                break
            end
        until s == ""
        -- log.info("uart", "after")
        readState=false
        end)     
    -- uart.write(uartid,string.char(0xBB, 0x00, 0x22, 0x00, 0x00, 0x22, 0x7E))      
        -- readRfid()   
    -- uart.write(uartid,string.char(0xBB,0x00,0x05,0x00,0x01,0x01,0x07,0x7E))
    -- uart.write(uartid,string.char(0xBB, 0x00, 0x27, 0x00, 0x03, 0x22,0x27,0x10,0x83, 0x7E))
    -- uart.write(uartid,string.char(0xBB,0x00,0x03,0x00,0x01,0x00,0x04,0x7E))
end

local function ComMain()
    log.info("--------------------ComMain--------------------------",uart.exist(0),uart.exist(1),uart.exist(2))
    ComInit()
end

local function Init()
    sys.taskInit(ComMain)
    sys.taskInit(readRfid)
end
dcom.Init = Init
return dcom

